<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Client\Contract\ClientContract;
use MoChat\App\Client\Model\Client;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 会员导出.
 * @Controller
 */
class Export extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ClientContract
     */
    protected $clientService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     *
     * @RequestMapping(path="/dashboard/client/export", methods="GET")
     */
    public function handle(): array
    {
        ini_set("max_execution_time", "0");
        ini_set("memory_limit", "5G");
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        // 校验参数
        $params = $this->request->all();
        $where = [];

        if ($params['mobile']) {
            $where[] = ['mobile', '=', $params['mobile']];
        }

        if ($params['b2bClientKeyword']) {
            $where[] = ['b2b_client_name', 'LIKE', '%' . $params['b2bClientKeyword'] . '%'];
        }
        if ($params['enterpriseKeyword']) {
            $where[] = ['enterprise_name', 'LIKE', '%' . $params['enterpriseKeyword'] . '%'];
        }
        if ($params['b2bSalesmanName']) {
            $where[] = ['b2b_salesman_name', 'LIKE', '%' . $params['b2bSalesmanName'] . '%'];
        }
        if ($params['b2bManagerName']) {
            $where[] = ['b2b_manager_name', 'LIKE', '%' . $params['b2bManagerName'] . '%'];
        }
        $list = Client::where($where)->orderByRaw('id desc')->get();
        $list || $list = collect([]);
        $list = $list->toArray();
        return $this->processingToTal($list);
    }

    /**
     * 组装基础数据
     * @param $tags
     * @return array
     */
    private function processingToTal($tags): array
    {
        $url = '';
        if (!empty($tags)) {
            $newExcel = new Spreadsheet();  //创建一个新的excel文档
            $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
            $objSheet->setTitle('客户列表');  //设置当前sheet的标题

            //设置宽度为true,不然太窄了
            $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
            $newExcel->getActiveSheet()->getColumnDimension('H')->setAutoSize(true);

            //设置第一栏的标题
            $objSheet->setCellValue('A1', '单位内码')
                ->setCellValue('B1', '企业名称')
                ->setCellValue('C1', '手机')
                ->setCellValue('D1', '客户类型')
                ->setCellValue('E1', '地址')
                ->setCellValue('F1', '注册时间')
                ->setCellValue('G1', '管理员(客服)')
                ->setCellValue('H1', '业务员');

            //第二行起，每一行的值,setCellValueExplicit是用来导出文本格式的。
            //->setCellValueExplicit('C' . $k, $val['admin_password']PHPExcel_Cell_DataType::TYPE_STRING),可以用来导出数字不变格式
            foreach ($tags as $k => $tag) {
                $k = $k + 2;
                $objSheet->setCellValue('A' . $k, $tag['uniqueId'])
                    ->setCellValue('B' . $k, $tag['enterpriseName'])
                    ->setCellValue('C' . $k, $tag['mobile'])
                    ->setCellValue('D' . $k, ClientTypeCode::getMessage($tag['b2bUserType']))
                    ->setCellValue('E' . $k, $tag['address'])
                    ->setCellValue('F' . $k, $tag['b2bRegisterTime'])
                    ->setCellValue('G' . $k, $tag['b2bManagerName'])
                    ->setCellValue('H' . $k, $tag['b2bSalesmanName']);
            }
            $url = $this->downloadExcel($newExcel, '客户列表', 'Xlsx');
        }
        return ['url' => $url];
    }

    //公共文件，用来传入xls并下载
    public function downloadExcel($newExcel, $filename, $format)
    {
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

//        $objWriter->save('php://output');
        //通过php保存在本地的时候需要用到
        $url = BASE_PATH . '/storage/upload/static' . '/客户列表.xlsx';
        $objWriter->save($url);
        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        //If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        return env('DASHBOARD_BASE_URL').'/api/static/客户列表.xlsx';
    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [
        ];
    }
}
